package club.xiaojiawei.strings;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 5/1/22 12:14 AM
 * @question 541.反转字符串II
 * @description 给定一个字符串 s 和一个整数 k，从字符串开头算起，每计数至 2k 个字符，就反转这 2k 字符中的前 k 个字符。
 * 如果剩余字符少于 k 个，则将剩余字符全部反转。
 * 如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。
 */
public class reverseStrII541 {

    public static void main(String[] args) {
        String s = "hyzqyljrnigxvdtneasepfahmtyhlohwxmkqcdfehybknvdmfrfvtbsovjbdhevlfxpdaovjgunjqlimjkfnqcqnajmebeddqsgl";
        String result = reverseStr(s, 39);
        System.out.println(result.equals("fdcqkmxwholhytmhafpesaentdvxginrjlyqzyhehybknvdmfrfvtbsovjbdhevlfxpdaovjgunjqllgsqddebemjanqcqnfkjmi"));
    }

    /**
     * 模拟
     * @param s
     * @param k
     * @return
     */
    public static String reverseStr(String s, int k) {
        char[] chars = s.toCharArray();
        int i = 0;
        char temp;
        int count;
        for (; i <= s.length() - k; i += (k << 1)){
            count = 1;
            for (int j = i; j < i + (k >> 1); j++){
                temp = chars[j];
                chars[j] = chars[k + i - count];
                chars[k + i - count] = temp;
                count++;
            }
        }
        if (s.length() % (k << 1) < k){
            count = 1;
            for (int j = i; j < ((i + chars.length) >> 1); j++){
                temp = chars[j];
                chars[j] = chars[chars.length - count];
                chars[chars.length - count] = temp;
                count++;
            }
        }
        return new String(chars);
    }

    /**
     * 官方-模拟
     * @param s
     * @param k
     * @return
     */
    public static String reverseStr2(String s, int k) {
        int n = s.length();
        char[] arr = s.toCharArray();
        for (int i = 0; i < n; i += 2 * k) {
            reverse(arr, i, Math.min(i + k, n) - 1);
        }
        return new String(arr);
    }

    public static void reverse(char[] arr, int left, int right) {
        while (left < right) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
}
